package org.ccs.cyperweb.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.ccs.cyperweb.service.SqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/sql")
public class SqlController {

	@Autowired
	private SqlService sqlService;

	@RequestMapping(value = "query", method = RequestMethod.GET)
	public String query() {
		return "sql/sql_query";
	}

	@RequestMapping(value = "query", method = RequestMethod.POST)
	public void executeQuery(HttpServletRequest request, Model model) {
		try {
			String sql = request.getParameter("sql");
			List list = sqlService.executeQuery(sql);

			model.addAttribute("ok", "true");
			model.addAttribute("msg", "create success!");
			model.addAttribute("result", list);
		} catch (Exception e) {
			model.addAttribute("ok", "false");
			model.addAttribute("msg", e.getMessage());
		}
	}
	
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public void executeUpdate(HttpServletRequest request, Model model) {
		try {
			String sql = request.getParameter("sql");
			String rows = sqlService.executeUpdate(sql);
			
			model.addAttribute("ok", "true");
			model.addAttribute("msg", "create success!");
			model.addAttribute("result", rows);
		} catch (Exception e) {
			model.addAttribute("ok", "false");
			model.addAttribute("msg", e.getMessage());
		}
	}

	public void setSqlService(SqlService sqlService) {
		this.sqlService = sqlService;
	}
}
